namespace TXLooker.WorkItemExtention.WIQL
{
    using System;

    public class NodeAndOperator : NodeVariableList
    {
        public NodeAndOperator() : base(NodeType.And)
        {
        }

        public override void Bind(IExternal e, NodeTableName tableContext, NodeFieldName fieldContext)
        {
            base.BindChildren(e, tableContext, fieldContext);
            for (int i = 0; i < this.Count; i++)
            {
                Tools.EnsureSyntax(this[i].DataType == DataType.Bool, SyntaxError.ExpectingBoolean, this[i]);
            }
            base.Bind(e, tableContext, fieldContext);
        }

        public override Node Optimize(IExternal e, NodeTableName tableContext, NodeFieldName fieldContext)
        {
            base.OptimizeChildren(e, tableContext, fieldContext);
            int i = 0;
            while (i < this.Count)
            {
                if (this[i].NodeType == NodeType.BoolConst)
                {
                    if (!((NodeBoolConst) this[i]).Value)
                    {
                        return new NodeBoolConst(false);
                    }
                    base.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }
            if (this.Count == 0)
            {
                return new NodeBoolConst(true);
            }
            if (this.Count == 1)
            {
                return this[0];
            }
            return base.Optimize(e, tableContext, fieldContext);
        }

        public override string ToString()
        {
            return base.JoinChildren(" and ");
        }

        public override DataType DataType
        {
            get
            {
                return DataType.Bool;
            }
        }

        public override Priority Priority
        {
            get
            {
                return Priority.AndOperator;
            }
        }
    }
}

